/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package DataAccess;

import Entity.BDoc;
import Servlet.PMF;
import java.util.Date;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

/**
 *
 * @author pdaitoan
 */
public class BDocAccess {
    PersistenceManager pm;
    public BDocAccess()
    {
        pm = PMF.get().getPersistenceManager();
    }
    public BDoc getBDocByID(Long BDocID)
    {
        String query = "select from " + BDoc.class.getName();
            List<BDoc> list = (List<BDoc>)pm.newQuery(query).execute();
            if (list.isEmpty() == false)
            for(BDoc bdoc : list)
            {
                if (bdoc.getBDocID() == BDocID)
                {
                    //pm.close();
                    return bdoc;
                }
            }
        pm.close();
        return null;
    }
    public Boolean addBDoc(BDoc bdoc)
    {
        try{
            pm.makePersistent(bdoc);
            return true;
        }
        catch(Exception e){
            return false;
        }
        finally
        {
            pm.close();
        }
    }
    public void deleteBDocByID(Long ID){
        BDoc bdoc = getBDocByID(ID);
        pm.deletePersistent(bdoc);
    }

    public List<BDoc> searchBDoc(String PubNum, String Subject, Date FromDate, Date ToDate) {
        Query q = pm.newQuery(BDoc.class);
        List<BDoc> results = null;
        if (!PubNum.trim().equals(("")))
        {
            q.setFilter("PubNum == pubnum && Subject == sub && ReceiveDate >= FromDate && ReceiveDate <= ToDate");
            q.declareImports("import java.util.Date");
            q.declareParameters("String pubnum, String sub,Date FromDate, Date ToDate");
            results = (List<BDoc>)q.executeWithArray(PubNum,Subject,FromDate,ToDate);
        }
        else if (!Subject.equals(""))
        {
            q.setFilter("Subject == sub && ReceiveDate >= FromDate && ReceiveDate <= ToDate");
            q.declareImports("import java.util.Date");
            q.declareParameters("String sub,Date FromDate, Date ToDate");
            results = (List<BDoc>)q.executeWithArray(Subject,FromDate,ToDate);
        }
        else if (FromDate != null && ToDate != null)
        {
            q.setFilter("ReceiveDate >= FromDate && ReceiveDate <= ToDate");
            q.declareImports("import java.util.Date");
            q.declareParameters("Date FromDate, Date ToDate");
            results = (List<BDoc>)q.executeWithArray(FromDate,ToDate);
        }
        else
            results = (List<BDoc>)q.execute();

        if (results.size() > 0)
            return results;
        return null;
    }

}
